package com.konsung.ksdc.manager.appmain;

import android.app.Fragment;
import android.app.FragmentTransaction;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.graphics.Color;
import android.net.ConnectivityManager;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.PopupWindow;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.konsung.ksdc.R;
import com.konsung.ksdc.common.network.RequestUtils;
import com.konsung.ksdc.common.utils.BroadCastActions;
import com.konsung.ksdc.common.utils.DensityUtils;
import com.konsung.ksdc.common.utils.ToastUtils;
import com.konsung.ksdc.common.widget.CommunityPopWindow;
import com.konsung.ksdc.config.MyApplication;
import com.konsung.ksdc.manager.community.ContactFragment;
import com.konsung.ksdc.manager.community.NoticeFragment;

import butterknife.Bind;
import butterknife.ButterKnife;

/**
 * 社区主界面
 *
 * Created by andy on 2017/4/13.
 */

public class CommunityFragment extends BaseFragment {
    @Bind(R.id.tv_msg)
    TextView tvMsg;
    @Bind(R.id.tv_contact)
    TextView tvContact;
    @Bind(R.id.iv_more)
    ImageView ivMore;
    @Bind(R.id.ll_conn_tips)
    RelativeLayout llConnTips;

    private Fragment noticeFragment;
    private Fragment contactFragment;
    private Fragment currentFragment;

    private CommunityPopWindow communityPopWindow; // 更多选项下拉框

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
    }

    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle bundle) {
        View view = View.inflate(getActivity(), R.layout.fragment_community, null);
        ButterKnife.bind(this, view);

        initTabEvent();
        initImgMoreEvent();
        initFragment();
        switchFragment(R.id.tv_msg);

        // 注册网络断开广播
        registerReceiver();
        return view;
    }

    /**
     * 初始化Fragment
     */
    private void initFragment() {
        noticeFragment = new NoticeFragment();
        contactFragment = new ContactFragment();
    }

    /**
     * 初始化头部tab按钮
     */
    private void initTabEvent() {
        tvMsg.setOnClickListener(new View.OnClickListener() {

            @Override
            public void onClick(View view) {
                tvMsg.setBackgroundResource(R.drawable.ic_xiaoxi_checked);
                tvMsg.setTextColor(Color.parseColor("#64d140"));
                tvContact.setBackgroundResource(R.drawable.ic_pengyou_unchecked);
                tvContact.setTextColor(Color.parseColor("#ffffff"));
                switchFragment(tvMsg.getId());
            }
        });

        tvContact.setOnClickListener(new View.OnClickListener() {

            @Override
            public void onClick(View view) {
                tvMsg.setBackgroundResource(R.drawable.ic_xiaoxi_unchecked);
                tvMsg.setTextColor(Color.parseColor("#ffffff"));
                tvContact.setBackgroundResource(R.drawable.ic_pengyou_checked);
                tvContact.setTextColor(Color.parseColor("#64d140"));
                switchFragment(tvContact.getId());
            }
        });
    }

    /**
     * 添加联系人弹出框
     */
    private void initImgMoreEvent() {

        ivMore.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                communityPopWindow = new CommunityPopWindow(getActivity(), null);
                communityPopWindow.setOnDismissListener(new PopupWindow.OnDismissListener() {
                    @Override
                    public void onDismiss() {

                    }
                });
                int width = getActivity().getWindow().getDecorView().getWidth();
                int popWidth = communityPopWindow.getWidth();
                communityPopWindow.showAtLocation(tvContact, 0,
                        width - popWidth - DensityUtils.dp2px(getActivity(), 3),
                        DensityUtils.dp2px(getActivity(), 60));
            }
        });
    }

    /**
     * 注册网络断开广播
     */
    private void registerReceiver() {
        IntentFilter intent = new IntentFilter();
        intent.addAction(ConnectivityManager.CONNECTIVITY_ACTION);
        getActivity().registerReceiver(receiver, intent);
    }

    /**
     * 广播接收者
     */
    private BroadcastReceiver receiver = new BroadcastReceiver() {
        @Override
        public void onReceive(Context context, Intent intent) {
            if (ConnectivityManager.CONNECTIVITY_ACTION.equals(intent.getAction())) {
                onNetworkChanged();
            }
        }
    };

    /**
     * 当网络状态发生变化
     */
    private void onNetworkChanged() {
        if (!RequestUtils.isNetworkConnected(getActivity())) {
            llConnTips.setVisibility(View.VISIBLE);
            ToastUtils.toastContent(MyApplication.getContext(),
                    MyApplication.getContext().getString(R.string.tip_check_net));
        } else {
            llConnTips.setVisibility(View.GONE);

            Intent intent = new Intent();
            intent.setAction(BroadCastActions.ACTION_RE_LOGIN);
            getActivity().sendBroadcast(intent);
        }
    }

    /**
     * 切换Fragment
     *
     * @param checkedId 选中项ID
     */
    private void switchFragment(int checkedId) {
        FragmentTransaction ft = getFragmentManager().beginTransaction();
        if (currentFragment != null) {
            ft.hide(currentFragment);
        }

        currentFragment = getFragmentManager().findFragmentByTag(checkedId + "");
        if (currentFragment == null) {
            if (R.id.tv_msg == checkedId) {
                currentFragment = noticeFragment;
            } else {
                currentFragment = contactFragment;
            }
            ft.add(R.id.fl_community_container, currentFragment, checkedId + "");
        } else {
            currentFragment.onResume();
            ft.show(currentFragment);
        }

        ft.commit();
    }

    @Override
    public void onAttach(Context context) {
        super.onAttach(context);
    }

    @Override
    public void onResume() {
        super.onResume();
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        getActivity().unregisterReceiver(receiver);
    }

    @Override
    protected void initEvent() {

    }

    @Override
    protected int getLayoutId() {
        return 0;
    }
}
